//
//  FIMainViewController.m
//  OpenglPing
//
//  Created by protocal 100TV on 12-11-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FIMainViewController.h"
#import "FIPlayViewController.h"
#import "ConstDef.h"
#import "FIVideoCell.h"
#import "xibhelp.h"
#import "mediatype.h"

@implementation VideoData
@synthesize mediaId;
@synthesize mediaUri;
@synthesize name;
@synthesize thumb_url;
@synthesize duration;
@synthesize createTime;
- (id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}
- (void)dealloc
{
    [mediaUri release];
    [name release];
    [thumb_url release];
    [super dealloc];
}
@end

////////////////////////////////////////////

@interface FIMainViewController ()

@end

@implementation FIMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        if (listData == nil) {
            listData = [[NSMutableArray alloc] init];
            [self listDumpFiles];
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem * btnitem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(doPlay:)];
    self.navigationItem.leftBarButtonItem = btnitem;
    [btnitem release];
    
    //gridview
    _m_gridview.dataSource = self;
    _m_gridview.delegate_grid = self;
    _m_gridview.isBookStore = YES;
    _m_gridview.left_width = 10;
}

- (void)doPlay:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Notice_Push_Play object:sender];
}

- (void)viewDidUnload
{
    [self setM_gridview:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [_m_gridview release];
    [listData removeAllObjects];
    [listData release];
    [super dealloc];
}

- (NSTimeInterval)fileTime:(NSString *)path {
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *attributesDic = [fileManager attributesOfFileSystemForPath:path error:&error];
    
    NSDate *date = [attributesDic objectForKey:NSFileModificationDate];
    return [date timeIntervalSince1970];
}
NSInteger sortVideoByNameAsc(id f1, id f2, void *context) {
    VideoData *video1 = (VideoData *)f1;
    VideoData *video2 = (VideoData *)f2;
    if (!video1.name || !video2.name) return NSOrderedSame;
    return [video1.name localizedCaseInsensitiveCompare:video2.name];
}
- (void)listDumpFiles {
	NSArray * directoryContent;
	NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * rootPath = [NSString stringWithString:docPath];
	if (![[NSFileManager defaultManager] fileExistsAtPath:rootPath]) {
		[[NSFileManager defaultManager] createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
	directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:rootPath error:nil];
    
	NSArray * supportFormat = [mediatype videoFormatExt];
	NSString * name = nil;
	for(int j = 0; j < [directoryContent count]; j++) {
		name = [directoryContent objectAtIndex:j];
        VideoData * videoInfo = [[VideoData alloc] init];
		if ([supportFormat containsObject:[[name pathExtension] lowercaseString]]) {
            NSString *mediaUriString = [rootPath stringByAppendingPathComponent:name];
			videoInfo.mediaId = j;
			videoInfo.name = name;
			videoInfo.mediaUri = mediaUriString;
            videoInfo.createTime = [self fileTime:[NSString stringWithFormat:@"%@/%@", rootPath, name]];
			[listData addObject:videoInfo];
		}
		[videoInfo release];
	}
    [[NSUserDefaults standardUserDefaults] setInteger:[listData count] forKey:@"VIDEO_COUNT"];
    [listData sortUsingFunction:sortVideoByNameAsc context:nil];
}

//gridview
-(unsigned int) numOfGridViewItem:(gridview*) agridView
{
    if (listData) {
        return [listData count];
    }
    return 0;
}
-(CGSize) sizeOfGridViewItem:(gridview*) agridView
{
    return CGSizeMake(100, 100);
}
-(gridviewcell*) gridView:(gridview*) agridView cellForIndex:(unsigned int) aindex
{
    VideoData * videoInfo = [listData objectAtIndex:aindex];
    
    static NSString * identifier = @"videocell";
    FIVideoCell * cell = (FIVideoCell*)[agridView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = (FIVideoCell*)[xibhelp loadObjectFromXIBName:@"FIVideoCell" type:[FIVideoCell class]];
    }
//    if (!videoInfo.thumb_url || videoInfo.duration == 0) {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            VideoData *videoData = [self getThumbnailImage:videoInfo.mediaUri width:71 height:78 pos:35000];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                videoInfo.thumb_url = videoData.thumb_url;
//                videoInfo.duration = videoData.duration;
//                [cell.videoImage setImage:[UIImage imageWithContentsOfFile:videoInfo.thumb_url]];
//            });
//            
//        });
//    }else {
//        [cell.videoImage setImage:[UIImage imageWithContentsOfFile:videoInfo.thumb_url]];
//    }
    cell.videoName.text = videoInfo.name;
    return cell;
}

-(void) gridView:(gridview*) agridView didSelectCellUp:(gridviewcell*) acell atIndex:(unsigned int) aindex
{
    VideoData * videoInfo = [listData objectAtIndex:aindex];
    NSLog(@"info:%@", videoInfo.mediaUri);
    [self doPlay:videoInfo.mediaUri];
}

@end








